package li.xiaobo;

import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.models.earth.atmosphere.data.CssiSpaceWeatherDataLoader;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeStamped;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.SortedSet;

public class Main {
    public static void main(String[] args) throws Exception {
        // 初始
        DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();

        // 加载
        manager.addProvider(new DirectoryCrawler(new File("orekit-data")));

        // 下载
        String method;
//        target = "file"; // 使用本地文件
        method = "url"; // 使用网络文件
        try (InputStream inputStream = open(method)) {
            // 1. 创建Loader
            TimeScale utc = DataContext.getDefault().getTimeScales().getUTC();
            CssiSpaceWeatherDataLoader loader = new CssiSpaceWeatherDataLoader(utc);

            // 2. 加载数据
            loader.loadData(inputStream, "SpaceWeather.txt");

            // 3. 读取
            SortedSet<TimeStamped> dataset = loader.getDataSet();
            System.out.println("VALUE TOTAL: " + dataset.size());

            // 遍历
            int index = 0;
            for (TimeStamped item : dataset) {
                CssiSpaceWeatherDataLoader.LineParameters line = (CssiSpaceWeatherDataLoader.LineParameters) item;

                AbsoluteDate date = line.getDate();
                double f107Obs = line.getF107Obs();
                double f107Adj = line.getF107Adj();
                double ap = line.getApAvg();

                System.out.printf(
                        "Date: %s, F10.7 Obs=%.1f, Adj=%.1f, ApAvg=%.1f\n",
                        date, f107Obs, f107Adj, ap
                );

                if (++index > 100) {
                    System.out.println("Only print 100 lines, exit.");
                    break;
                }
            }
        }
    }

    private static InputStream open(String method) throws Exception {
        if ("url".equals(method)) {
            return openUrl();
        }
        return openFile();
    }

    public static InputStream openFile() throws Exception {
        String name;
        name = "SW-5YEARS.txt";
//        name = "SW-Last5Years.txt";
        System.out.println("Open file: " + name);
        return new File(name).toURI().toURL().openStream();
    }

    public static InputStream openUrl() throws Exception {
        // 使用国内数据供应商提供的数据，不需要科学上网
        String url = "https://spacemapper.cn/cgi/space/weather/file/SW-5YEARS.txt?rid=24e670d8c0f7406cbfb0732720309030";
        System.out.println("Open url: " + url);
        return new URL(url).openStream();
    }
}